from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

def setup_swagger_ui(app: FastAPI) -> None:
    """
    设置FastAPI的Swagger UI，添加API密钥授权功能
    
    Args:
        app: FastAPI应用实例
    """
    
    def custom_openapi():
        if app.openapi_schema:
            return app.openapi_schema
        
        openapi_schema = get_openapi(
            title=app.title,
            version=app.version,
            description=app.description,
            routes=app.routes,
        )
        
        # 添加API密钥安全方案
        openapi_schema["components"] = openapi_schema.get("components", {})
        openapi_schema["components"]["securitySchemes"] = {
            "ApiKeyAuth": {
                "type": "apiKey",
                "in": "header",
                "name": "X-API-Key"
            }
        }
        openapi_schema["security"] = [{"ApiKeyAuth": []}]
        
        app.openapi_schema = openapi_schema
        return app.openapi_schema
    
    # 设置自定义OpenAPI函数
    app.openapi = custom_openapi